import React, { Component, useState, useEffect } from 'react';
import { Button } from 'antd';
import { viewUtils } from '@/utils/arcgis';
import classnames from 'classnames';
import styles from './index.less';
const SearchResultList = ({ models, keyword, onItemClick, onPlaceholderClick }) => {
  const data = models;
  const [curLayers, setCurLayers] = useState([]);
  const [resultLayers, setResultLayers] = useState([]);
  useEffect(() => {
    _getCurLayers();
  }, []);

  useEffect(() => {
    const result = keyword ? curLayers.filter((s) => s.indexOf(keyword) !== -1) : curLayers;
    setResultLayers(result);
  }, [curLayers, keyword]);

  const _getCurLayers = async () => {
    const view = await viewUtils.isViewReady();
    const _curLayers = view.map.layers.map((e) => e.title);
    setCurLayers(_curLayers);
  };

  const handleItemClick = async (item) => {
    onItemClick(item);
    const view = await viewUtils.isViewReady();
    const layer = view.map.layers.reduce((result, e) => {
      if (e.title === item.name) {
        result.push(e);
      }
      return result;
    }, [])[0];
    view.goTo(layer.fullExtent);
  };
  if (!curLayers.length) {
    return (
      <ul className={classnames(styles.resultList, styles.resultListEmpty)}>
        <Button type="link" onClick={onPlaceholderClick}>
          暂无bim图层，请去图层列表添加
        </Button>
      </ul>
    );
  }
  return (
    <ul className={styles.resultList}>
      {!!data.length &&
        data
          .filter((e) => {
            return resultLayers.indexOf(e.name) !== -1;
          })
          .map((e, i) => {
            const index = e.name.indexOf(keyword);
            const beforeStr = e.name.substr(0, index);
            const afterStr = e.name.substr(index + keyword.length);
            const title =
              index > -1 ? (
                <span>
                  {beforeStr}
                  <span style={{ color: '#f69402' }}>{keyword}</span>
                  {afterStr}
                </span>
              ) : (
                <span>{e.name}</span>
              );
            return (
              <li onClick={() => handleItemClick(e)} className={styles.resultListItem} key={i}>
                {title}
              </li>
            );
          })}
    </ul>
  );
};

export default SearchResultList;
